package com.geline.demo.web;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geline.demo.dto.TownHouseListQry;
import com.geline.demo.entity.ExcelFile;
import com.geline.demo.service.ExcelFileService;
import com.geline.easyexcel.domain.ReportResult;
import com.geline.easyexcel.manager.EasyExcelManager;
import com.geline.easytrans.service.EasyTransService;
import com.geline.extension.domain.PageQuery;
import com.geline.extension.domain.Result;
import com.geline.extension.util.QueryWrapperUtil;
import com.geline.mybatisplus.annotation.SQLFieldImportCache;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通用excel导入导出
 *
 * @author: mengxin
 * @date: 2023/9/13 20:48
 */
@RestController
@Tag(name = "easyExcel", description = "Excel接口")
@RequestMapping("/api/easyExcel")
@Slf4j
public class EasyExcelController {

    @Autowired
    private EasyExcelManager excelManager;

    /**
     * http://localhost:8080/api/easyExcel/exportPageTemplate/{entityName}
     * http://localhost:8080/api/easyExcel/exportPageTemplate/townHouse?pageIndex=1&pageSize=10
     * 支持生成下拉框（单选下拉，多选下拉，级联下拉）
     *
     * @param response
     */
    @Operation(summary = "分页查询-下载Excel模板", description = "下载Excel模板")
    @GetMapping("/exportPageTemplate/{entityName}")
    public void exportPageTemplate(@PathVariable String entityName, HttpServletResponse response) {
        excelManager.exportPageTemplate(response, entityName);
    }

    /**
     * http://localhost:8082/api/easyExcel/exportListTemplate/{reportCode}
     * 支持生成下拉框（单选下拉，多选下拉，级联下拉）
     *
     * @param response
     */
    @Operation(summary = "统计汇总-下载Excel模板", description = "下载Excel模板")
    @GetMapping("/exportListTemplate/{reportCode}")
    public void exportListTemplate(@PathVariable String reportCode, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> query = getConditionMap(request);
        excelManager.exportListTemplate(response, reportCode, query);
    }

    /**
     * 支持生成下拉框（单选下拉，多选下拉，级联下拉）
     * /api/easyExcel/exportListExcel/{reportCode}?name=xxx&code=xxx
     * @param reportCode
     * @param request
     * @param response
     */
    @Operation(summary = "统计汇总-导出Excel", description = "导出Excel")
    @GetMapping("/exportListExcel/{reportCode}")
    public void exportListExcel(@PathVariable String reportCode, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> query = getConditionMap(request);
        excelManager.exportListExcel(response, reportCode, query);
    }

    /**
     * 查询统计报表数据
     * localhost:8083/services/examination-app/api/easyExcel/getReportResult/{reportCode}
     * localhost:8083/services/examination-app/api/easyExcel/getReportResult/illegalConstructionStatistics?xzqhdm=440100000&curXzqhdm=440100000&year=2024&startMonth=1&endMonth=2
     * @param reportCode
     * @param request
     */
    @Operation(summary = "统计汇总-查询列表数据", description = "查询统计报表数据")
    @GetMapping("/getReportResult/{reportCode}")
    public ReportResult getReportResult(@PathVariable String reportCode, HttpServletRequest request) {
        Map<String, Object> query = getConditionMap(request);
        return excelManager.getReportResult(reportCode, query);
    }

    /**
     * 导入Excel
     * localhost:8083/services/examination-app/api/easyExcel/importExcel/{entityName}
     * localhost:8083/services/examination-app/api/easyExcel/importExcel/townHouse
     *
     *  导入失败时，下载excel - https://blog.csdn.net/weixin_44136661/article/details/118088837
     * @param multipartFile
     * @return
     * @throws IOException
     */
    @SQLFieldImportCache
    @Operation(summary = "Excel导入", description = "Excel导入")
    @PostMapping("/importExcel/{entityName}")
    public Result importExcel(@PathVariable String entityName, @RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        try {
            String errorId = excelManager.parseExcelAndSaveError(entityName, multipartFile, getConditionMap(request));
            if(StrUtil.isNotBlank(errorId)){
                return Result.fail("Excel数据检验异常，请下载查看已加批注Excel！", errorId);
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            return Result.fail("非法Excel，表头不匹配！");
        }
        return Result.ok("导入成功!");
    }

    /**
     * 下载错误Excel：带批注
     * localhost:8083/services/examination-app/api/easyExcel/downErrorExcel/{entityName}?errorId=xxx
     * @param entityName
     * @param errorId
     * @param response
     * @throws IOException
     */
    @Operation(summary = "下载错误Excel：带批注", description = "下载错误Excel：带批注")
    @GetMapping("/downErrorExcel/{entityName}")
    public void downErrorExcel(@PathVariable String entityName, String errorId, HttpServletResponse response) throws IOException {
        excelManager.downErrorExcel(response, entityName, errorId);
    }

    /**
     * 查询组装请求参数
     *
     * @param request
     * @return
     */
    private Map<String, Object> getConditionMap(HttpServletRequest request) {
        Map<String, Object> conditionMap = new HashMap();
        Enumeration paraNames = request.getParameterNames();
        while (paraNames.hasMoreElements()) {
            String name = (String) paraNames.nextElement();
            String value = request.getParameter(name);
            if (value != null && conditionMap.get(name) == null) {
                conditionMap.put(name, value.trim());
            }
        }
        return conditionMap;
    }
}
